import { ref } from 'vue'

import { back, catchFn } from '@/libs/common'
import { getQuizResult } from '../../api'
import { userInfo } from '@/libs/user'
import { payOption } from './unlock-mask/data'
import { getAvatar, uploadAvatar, getInviteCount } from './api'
import { chooseImages, imagePathOnly } from '@/libs/file-utils'
import { getCanvas, getCanvasImage, getImageInstance } from '@/components/OffScreenCanvas/data'
import { poster } from '@/pages/community/friend/report/data'
import { topMessage } from '@/components/TopMessage/data'

/** MBTI测试结果 */
const result = ref<T_MBTIResult>()
/**
 * 报告类型
 * 0 未解锁
 * 2 初级报告
 * 3 高级报告
 */
const resultType = ref<0 | 2 | 3>(0)
/** 用户头像 */
const userAvatar = ref('')

let resultId = 0

/** 邀请人数 */
const inviteCount = ref(0)
/** 需要邀请人数 */
const totalCount = ref(0)

// const elementaryList = [
//   {
//     title: '潜意识：',
//     key: 'subconscious',
//   },
//   {
//     title: '负面情绪',
//     key: 'negativeEmotions',
//   },
//   {
//     title: '内心恐惧',
//     key: 'innerFear',
//   },
//   {
//     title: '核心共性',
//     key: 'coreCommonalities',
//   },
//   {
//     title: '优秀领域',
//     key: 'strengths',
//   },
//   {
//     title: '蒜蒜建议',
//     key: 'suggestion',
//   },
// ]

// const advancedList = [
//   {
//     title: '爱情',
//     key: 'love',
//   },
//   {
//     title: '健康',
//     key: 'health',
//   },
//   {
//     title: '财务',
//     key: 'money',
//   },
//   {
//     title: '职业',
//     key: 'work',
//   },
//   {
//     title: '事业',
//     key: 'career',
//   },
// ]
// const curAdvancedIdx = ref(0)

export {
  result,
  resultType,
  userAvatar,
  resultId,
  inviteCount,
  totalCount,
  // elementaryList,
  // advancedList,
  // curAdvancedIdx,
}

let lastCode = 'mbti_28'
let lastSession = ''

/**
 * 更新测试结果
 * @param typeCode 测试类型
 * @param sessionId 会话ID
 */
const update = (typeCode = lastCode, sessionId = lastSession) =>
  catchFn(async () => {
    const { data } = await getQuizResult({ typeCode, sessionId })

    lastCode = typeCode
    lastSession = sessionId

    const manual = data.mbtiResult.instructionManual

    if (manual) {
      manual.femaleProportionNumber = Math.round(manual.femaleProportionNumber * 100)
      manual.maleProportionNumber = Math.round(manual.maleProportionNumber * 100)
      manual.rarityNumber = Math.round(manual.rarityNumber * 100)
    } else {
      back()
      setTimeout(() => topMessage.warn('报告还未生成，请耐心等待~'), 500)
    }

    result.value = data.mbtiResult
    resultType.value = data.unlockedType
    userInfo.value = data.userInfo
    payOption.testType = data.mbtiResult.typeCode
    resultId = payOption.testResultId = data.id

    result.value.dimensions[0].color = '#6E26FF'
    result.value.dimensions[1].color = '#FFB516'
    result.value.dimensions[2].color = '#00BF0D'
    result.value.dimensions[3].color = '#1362FF'

    userInfo.value?.avatar &&
      getAvatar(userInfo.value?.avatar).then(({ data }) => (userAvatar.value = data.url))

    resultType.value < 2 && startUpdateInviteCount(data.sessionId, data.id)

    return true
  })

let checkTimeout: any = null

const startUpdateInviteCount = async (sessionId: string, id: number) => {
  const res = await getInviteCount(sessionId, id)

  inviteCount.value = res.data.inviteCount
  totalCount.value = res.data.totalCount

  inviteCount.value < totalCount.value &&
    (checkTimeout = setTimeout(() => {
      checkTimeout = null
      startUpdateInviteCount(sessionId, id)
    }, 10000))
}

/**
 * 上传头像
 */
const clickAvatar = () => {
  chooseImages(1, ({ tempFiles }) => {
    const file: any = Array.isArray(tempFiles) ? tempFiles[0] : tempFiles

    catchFn(async () => {
      const res = await uploadAvatar(file.path)

      userAvatar.value = res.data.url
    })
  })
}

/**
 * 合成海报
 */
const createPoster = () =>
  catchFn(async () => {
    if (!result.value) throw '数据缺失'

    const { ctx } = await getCanvas()

    // 获取海报
    const img_poster = await getImageInstance(imagePathOnly('quiz/mbti/result/poster-bg.jpg'))

    // 合成
    const w = img_poster.width
    const h = img_poster.height

    await getCanvas(w, h)

    // 1. 底色
    ctx.fillStyle = '#F6BDCE'
    ctx.fillRect(0, 0, w, h)

    // 2. 底图
    ctx.drawImage(img_poster, 0, 0, w, h)

    // 3. 标题
    {
      const title = `${userInfo.value?.nickname || ''}的蒜蒜报告`

      ctx.font = '70px ChillRoundM'

      const test = ctx.measureText(title)
      const left = 375 - test.width / 2
      const top = 62 + 96

      ctx.fillStyle = '#fff'
      ctx.shadowOffsetX = 0
      ctx.shadowOffsetY = 8
      ctx.shadowBlur = 14
      ctx.shadowColor = '#CE2863'
      ctx.fillText(title, left, top)
    }

    // 4. 标题
    // {
    //   ctx.font = '32px ChillRoundM'
    //   ctx.fillStyle = '#88268B'
    //   ctx.fillText('我的测试结果', 32, 416)
    //   ctx.fillText('我的性格特点', 100, 664)
    // }

    // 5. MBTI
    {
      const t1 = `${result.value?.fullType || ''}+${userInfo.value?.zodiacSign || ''}`
      // const t2 = result.value?.archetype || ''

      ctx.font = '48px ChillRoundM'
      ctx.fillStyle = '#fff'
      ctx.shadowOffsetX = 0
      ctx.shadowOffsetY = 2
      ctx.shadowBlur = 8
      ctx.shadowColor = '#E869CD'

      const test = ctx.measureText(t1)
      const left = 375 - test.width / 2

      ctx.fillText(t1, left, 240+46)
    }

    // 6. 性格
    {
      ctx.font = '28px ChillRoundM'
      ctx.fillStyle = '#6F3949'
      ctx.shadowOffsetX = 0
      ctx.shadowOffsetY = 0
      ctx.shadowBlur = 0
      ctx.shadowColor = '#0000'

      drawText(ctx, result.value?.description || '', 74, 1000)
    }

    // 7. 水印
    if (userInfo.value?.watermark) {
      const img_watermark = await getImageInstance(imagePathOnly('watermark.png'))

      for (let i = 0; i < 15; i++) {
        for (let j = 0; j < 2; j++) {
          ctx.fillStyle = '#ffffff55'
          ctx.drawImage(img_watermark, 440 * j + (i % 2 == 0 ? -50 : 170), 110 * i, 220, 100)
        }
      }
    }

    // final. 导出
    poster.value = await getCanvasImage()

    // #ifdef MP-WEIXIN
    uni.showShareImageMenu({
      path: poster.value,
      // @ts-ignore
      entrancePath: '/pages/index/index',
    })
    // #endif
    // #ifndef MP-WEIXIN
    uni.navigateTo({ url: '/pages/community/friend/report/poster' })
    // #endif
  })

/**
 * 绘制多行文字
 * @param ctx 画布
 * @param text 文字内容
 * @param x 坐标X
 * @param y 坐标Y
 */
const drawText = (ctx: any, text: string, x: number, y: number) => {
  const chars = text.split('')

  // 逐行绘制
  let line = ''

  for (const ch of chars) {
    const testLine = line + ch
    const testWidth = ctx.measureText(testLine).width

    if (testWidth > 602) {
      ctx.fillText(line, x, y)
      y += 36
      line = ch
    } else {
      line = testLine
    }
  }

  ctx.fillText(line, x, y)
}

/**
 * 还原状态
 */
const clear = () => {
  lastCode = 'mbti_28'
  lastSession = ''

  result.value = undefined
  resultId = 0
  resultType.value = 0
  // curAdvancedIdx.value = 0

  checkTimeout && clearTimeout(checkTimeout)
}

export { update, clickAvatar, createPoster, clear }
